package com.nutiteq.mapper.forms;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import com.nutiteq.MapComponent;
import com.nutiteq.mapper.MapScreen;
import com.nutiteq.mapper.Mapper;

public class ResizeForm extends Form implements CommandListener {
  public static final Command RESIZE_COMMAND = new Command("Resize component", Command.ITEM, 0);

  private static final Command BACK = new Command("Back", Command.BACK, 0);
  private static final Command RESIZE = new Command("Resize", Command.ITEM, 0);

  private final int minWidth;
  private final int minHeight;
  private final int maxWidth;
  private final int maxHeight;
  private final MapComponent mapDisplay;

  private TextField width;
  private TextField height;

  public ResizeForm(final int minWidth, final int minHeight, final int maxWidth,
      final int maxHeight, final MapComponent mapDisplay) {
    super("Resize map component");
    this.minWidth = minWidth;
    this.minHeight = minHeight;
    this.maxWidth = maxWidth;
    this.maxHeight = maxHeight;
    this.mapDisplay = mapDisplay;

    width = new TextField("Component width (" + minWidth + " - " + maxWidth + ")", Integer
        .toString(maxWidth), Integer.toString(maxWidth).length(), TextField.ANY);
    height = new TextField("Component height (" + minHeight + " - " + maxHeight + ")", Integer
        .toString(maxWidth), Integer.toString(maxHeight).length(), TextField.ANY);

    append(width);
    append(height);

    addCommand(BACK);
    addCommand(RESIZE);
    setCommandListener(this);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == BACK) {

    } else if (cmd == RESIZE) {
      final int widthTmp = parseInt(width.getString(), maxWidth);
      final int heightTmp = parseInt(height.getString(), maxHeight);
      mapDisplay.resize(widthTmp >= minWidth && widthTmp <= maxWidth ? widthTmp : maxWidth,
          heightTmp >= minHeight && heightTmp <= maxHeight ? heightTmp : maxHeight);

    }
    Display.getDisplay(Mapper.instance).setCurrent(MapScreen.instance);
  }

  private int parseInt(final String numberString, final int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(numberString);
    } catch (NumberFormatException e) {}

    return result;
  }
}
